package com.wb.server.udp.server;

import com.wb.server.processor.DataProcessorFactory;
import com.wb.server.processor.impl.DefaultDataProcessor;
import com.wb.server.tcp.server.AbstractIecServer;
import com.wb.server.udp.server.handler.UdpServerHandler;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioDatagramChannel;
import lombok.extern.slf4j.Slf4j;

/**
 * @Author chenyong
 * @Description TODO
 * @Date 2022/12/11 11:25
 * @Version 1.0
 */
@Slf4j
public class UdpCollectServer extends AbstractIecServer {

    public UdpCollectServer(){
        this.dataProcessorFactory=new DefaultDataProcessor();
    }

    public UdpCollectServer(DataProcessorFactory processor){
        this.dataProcessorFactory=processor;
    }

    @Override
    public void startServer(int port){
        NioEventLoopGroup main = new NioEventLoopGroup(1);

        Bootstrap bootstrap=new Bootstrap();

        bootstrap.group(main)
                .channel(NioDatagramChannel.class)
                .option(ChannelOption.SO_BROADCAST, true)
                .handler(new ChannelInitializer<NioDatagramChannel>() {

                    @Override
                    protected void initChannel(NioDatagramChannel channel) throws Exception {
                        ChannelPipeline pipeline = channel.pipeline();
                        pipeline.addLast(new UdpServerHandler(dataProcessorFactory));
                    }
                });
        try {
            ChannelFuture future = bootstrap.bind(port).sync();
            log.info("Collect server is start on port: {}(UDP).", port);
            future.channel().closeFuture().sync();
        } catch (InterruptedException e) {
            log.info("udp server shut down");
            e.printStackTrace();
        }finally {
            main.shutdownGracefully();
        }

    }
}
